package club.baimahu.pencil.servlet;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import lombok.Data;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

@Data
public class HttpServletRequest {

    private ChannelHandlerContext ctx;
    private FullHttpRequest fullHttpRequest;

    public HttpServletRequest(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest){
        this.ctx = ctx;
        this.fullHttpRequest = fullHttpRequest;
    }

    public String getUri() {
        String uri = fullHttpRequest.uri();
        String[] s = uri.split("\\?");
        if (s.length < 2) {
            return uri;
        }
        return s[0];
    }

    public Map<String,List<String>> getParameters(){
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(this.fullHttpRequest.uri());
        return queryStringDecoder.parameters();
    }


    public JSONObject getJSON(){
        ByteBuf byteBuf =this.fullHttpRequest.content();
        String str = byteBuf.toString(Charset.forName("utf-8"));

        return JSONObject.parseObject(str);
    }


    public String getParameter(String key){
        Map<String,List<String>> map = getParameters();
        if(map.containsKey(key)){
            return null;
        }else{
            return map.get(key).get(0);
        }
    }




}
